<template>
  <el-dialog :width="changeRem(width)" :title="title" :visible.sync="visible" append-to-body>
   <div class="option-box" v-loading="loading">
     <el-input
       v-if="canFilter"
       placeholder="输入关键字进行过滤"
       v-model="filterText">
     </el-input>
     <el-scrollbar>
       <div style="height:300px">
         <el-tree ref="tree"
                  :highlight-current="true"
                  :filter-node-method="filterNode"
                  :current-node-key="currentNodeKey"
                  :expand-on-click-node="canSelectParent"
                  :data="optionsData" v-bind="$attrs" :node-key="props.value"
                  :default-checked-keys="checkedValuesId" :props="props"
                  :show-checkbox="multiple" v-on="$listeners"
                  @node-click="handleNodeClick"
                  @check-change="handleCheckChange"></el-tree>
       </div>
     </el-scrollbar>
   </div>
    <div slot="footer" class="dialog-footer clearfix" style="text-align: right">
        <span class="btn-box" style="text-align: right;display: flex">
           <el-button @click="visible = false" size="small">取 消</el-button>
           <el-button type="primary" size="small" @click="confirm">确 定</el-button>
        </span>
    </div>
  </el-dialog>
</template>

<script>
import BaseRequestComponent from "../../BaseRequestComponent";
import arr from "../../../../../utils/function/arr";

export default {
  name: 'searchTreeDialogType2',
  extends:BaseRequestComponent,
  props: {
    visibleValue: {
      required: true,
      type: Boolean
    },
    width: {
      default: '750px'
    },
    url: {
      required: true,
      type: String
    },
    params: {
      type: Object,
      default: () => ({
      })
    },
    options: Array, // 选项
    paramsMap: {
      type: Object,
      default: () => ({
      })
    },
    // 默认的props
    props: Object,
    value:[Object,Array,Number,String],
    title: {
      default: '搜索'
    },
    searchKey: { // 查询请求的key
      default: 'nameOrNumber'
    },
    multiple: {
      type: Boolean,
      default: () => false
    }, // 是否多选
    includeParent: {
      type: Boolean,
      default: () => false
    }, // 是否包含 父亲
    canSelectParent: {
      type: Boolean,
      default: () => false
    }, // 是否能够选中 父亲
    canFilter: {
      type: Boolean,
      default: () => false
    }, // 是否能够过滤
  },
  data() {
    return {
      filterText: '',
      queryParams:{},
      visible: false,
      dataList: [],
      activeItem: {},
      // 当前页选中的
      checkedValues: [],
      checkedValuesId: this.value || [],
      // 所有的选中的
      checkedValuesAllObj: [],
      loading: false,
      optionsData:[],
      allArrs: [], // 所有的数组
      currentNodeKey:"",
    }
  },
  mounted() {
    this.$forceUpdate()
  },
  updated() {
    if (!this.multiple){
      this.currentNodeKey = this.value
      if (this.currentNodeKey && this.currentNodeKey.toString()){
        this.$refs.tree.setCurrentKey(this.currentNodeKey)
      }else{
        this.$refs.tree.setCurrentKey(null)
      }
    }
  },
  methods: {
    async search (url = this.url) {
      const param = this.params
      this.loading = true
      await this.getDict(url,param,this.$attrs.method || 'get')
      .then(res => {
        let status = eval(`res.${this.getDictResultMap.status}`)
        let data = eval(`res.${this.getDictResultMap.data}`)
        if (status === this.getDictSuccessStatus){
          this.optionsData = data
        }
      }).finally(() => {
        this.loading = false
      })
    },
    changeRem(number) {
      return (parseFloat(number) * Math.min(this.$scale, 1)) + 'px'
    },
    handleNodeClick(data,i){
      if (!this.canSelectParent && data && data[this.props.children]){
        return this.$message.info("不能选择父节点")
      }
      if (!this.multiple) {
        this.$emit('dialogDataChange',data)
        this.visible = false
      } else {
        this.$emit('dialogDataChange',this.checkedValues)
      }
    },
    // 获取所有的子元素，然后放到一个数组里面
    getAllChildren(obj){
      let arrs = []
      arrs.push(obj)
      if (obj[this.props.children] && obj[this.props.children].length){
        if (!this.includeParent) arrs.pop()
        obj[this.props.children].map(item=>{
          arrs.push(...this.getAllChildren(item))
        })
        return arrs
      }else{
        return arrs
      }
    },
    handleCheckChange(data, checked, indeterminate){
      if (checked){// 表明没有的情况下，添加进去
        if (this.multiple) {
          let temp = this.getAllChildren(data)
          console.log('获取选中后的所有',temp)
          temp.map(item=>{
            if (!this.checkedValues.find(a=>a[this.props.value]===item[this.props.value])) {
              this.checkedValues.push(item)
            }
          })
          console.log('处理选中后的所有',this.checkedValues)
        }else{
          this.checkedValues.push(data)
        }
      }else{
        if (this.multiple) {
          let temp = this.getAllChildren(data)
          temp.map(item=>{
            if (this.checkedValues.find(a=>a[this.props.value]===item[this.props.value])) {
              this.checkedValues = this.checkedValues.filter(i=>i[this.props.value]!==data[this.props.value])
            }
          })
        }else{
          if (this.checkedValues.find(a=>a[this.props.value]===data[this.props.value])) {
            this.checkedValues = this.checkedValues.filter(i=>i[this.props.value]!==data[this.props.value])
          }
        }
      }
      console.log("选中后",this.checkedValues)
      this.checkedValues = arr(this.checkedValues).unique(this.props.value).all()
      console.log("选中后去重复",this.checkedValues)
    },
    filterNode(value, data) {
      if (!value) return true;
      return data[this.props.label].indexOf(value) !== -1;
    },
    confirm() {
      if (!this.multiple) {
        this.$emit('dialogDataChange',this.activeItem)
        this.visible = false
      } else {
        this.checkedValues = arr(this.checkedValues).unique(this.props.value).all()
        this.$emit('dialogDataChange',this.checkedValues)
        this.checkedValuesId = arr(this.checkedValues).pluck(this.props.value).all()
      }
      this.visible = false
    },
  },
  watch: {
    visibleValue: {
      handler (val) {
        if (val !== this.visible) this.visible = val
        if (val && this.url) {
          this.search()
        }
      },
      immediate: true
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    value(val) {
      if (!this.multiple){
        this.currentNodeKey = val
      }
      console.log('当前选择的节点',this.currentNodeKey)
    },
    visible (val) {
      if (this.visibleValue !== val) this.$emit('update:visibleValue', val)
    },
  }
}
</script>

<style scoped lang="scss">
  .option-box {
    height: 300px;
  }
  .drawing-list-wrap{
    padding: 0px;
    height: 300px;
    .list-item{
      list-style: none;
      margin: 0;
      cursor: pointer;
      padding: 12px 0 12px 5px;
      transition: all .3s ease-in;
      &:hover{
        background-color: #F5F7FA;
      }
      &:active {
        background-color: #409EFF;
      }
      border-bottom: 1px solid #f4f5f6;
    }
    .active-item {
      color: #409EFF;
    }
    ::v-deep .el-checkbox {
      display: inherit;
      margin: 0;
      padding: 12px 0 12px 5px;
      transition: all .3s ease-in;
    }
  }
  ::v-deep.el-scrollbar__wrap{
    overflow-x: hidden;
  }
  ::v-deep .el-icon-circle-check {
    display: none;
  }
.cursor{
  cursor: pointer;
}
  .dialog-footer {
    width: 100%;
    .page-box {
      float: left;
    }
    .btn-box {
      float: right;
    }
  }
</style>
